import { ref, watch, onMounted } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
export function useToggleSort (props) {
  // 加载更多功能
  const isFinished = ref(false) // 是否全部加载完毕
  const isLoading = ref(true)

  // 导航功能
  // 排序切换
  const sorTypeListRef = ref([
    { name: '默认', value: null },
    { name: '时间', value: 'publishTime' },
    { name: '人气', value: 'orderNum' },
    { name: '评论', value: 'evaluateNum' }
  ])
  const curSortTypeRef = ref(null)

  function toggleSort (sortType) {
    curSortTypeRef.value = sortType
    reqParams.sortField = sortType
    reqParams.page = 1
    loadData()
  }

  const route = useRoute()

  // 商品功能
  // 获取list
  const goodList = ref([])
  // 请求参数
  const reqParams = {
    page: 0,
    pageSize: 20,
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: props.keyWord, // 商品属性
    brandId: null // 品牌名称
  }

  watch(() => {
    return props.keyWord
  }, () => {
    reqParams.page = 1
    loadData()
  }, {
    deep: true
  })

  async function loadData () {
    const res = await findSubCategoryGoods(reqParams)
    goodList.value = res.result.items
  }
  onMounted(() => {
    // loadData()
    isLoading.value = false
  })

  // 加载更多功能
  // 是否正处于数据获取中 默认值为true 因为在页面一上来的时候mounted中就已经开始加载第一页数据了
  // 等到数据获取到之后再把isLoading设置为false
  async function loadNextList () {
    isLoading.value = true
    reqParams.page++
    const res = await findSubCategoryGoods(reqParams)
    const newList = res.result.items
    if (newList.length === 0) {
      // 停止监听
      isFinished.value = true
    }
    goodList.value = [...goodList.value, ...res.result.items]
    isLoading.value = false
  }

  return {
    sorTypeListRef,
    toggleSort,
    goodList,
    curSortTypeRef,
    isFinished,
    isLoading,
    loadNextList
  }
}
